using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 数据清理功能控制台测试程序
    /// </summary>
    public class TestDataCleanupConsole
    {
        /// <summary>
        /// 运行数据清理测试的主入口
        /// </summary>
        public static async Task RunAsync()
        {
            try
            {
                Console.WriteLine("=== 数据库清理工具测试 ===");
                Console.WriteLine();

                // 创建服务提供者
                var services = new ServiceCollection();
                ConfigureServices(services);
                var serviceProvider = services.BuildServiceProvider();

                // 创建测试实例
                var testCleanup = new TestDataCleanup(serviceProvider);

                // 显示菜单
                while (true)
                {
                    ShowMenu();
                    var choice = Console.ReadLine()?.Trim();

                    switch (choice)
                    {
                        case "1":
                            await RunIntegrityCheck(testCleanup);
                            break;
                        case "2":
                            await RunDataCleanup(testCleanup);
                            break;
                        case "3":
                            await CreateBackup(testCleanup);
                            break;
                        case "4":
                            await ViewBackups(testCleanup);
                            break;
                        case "5":
                            await RunFullTest(testCleanup);
                            break;
                        case "0":
                            Console.WriteLine("退出程序...");
                            return;
                        default:
                            Console.WriteLine("无效选择，请重新输入。");
                            break;
                    }

                    Console.WriteLine();
                    Console.WriteLine("按任意键继续...");
                    Console.ReadKey();
                    Console.Clear();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"程序运行出错: {ex.Message}");
                Console.WriteLine($"详细错误: {ex}");
            }
        }

        private static void ShowMenu()
        {
            Console.WriteLine("数据库清理工具测试菜单:");
            Console.WriteLine("1. 检查数据完整性");
            Console.WriteLine("2. 执行数据清理");
            Console.WriteLine("3. 创建数据备份");
            Console.WriteLine("4. 查看备份列表");
            Console.WriteLine("5. 运行完整测试");
            Console.WriteLine("0. 退出");
            Console.WriteLine();
            Console.Write("请选择操作 (0-5): ");
        }

        private static async Task RunIntegrityCheck(TestDataCleanup testCleanup)
        {
            Console.WriteLine("正在检查数据完整性...");
            Console.WriteLine();

            try
            {
                var dataStorage = App.ServiceProvider?.GetService<IDataStorageService>();
                if (dataStorage == null)
                {
                    Console.WriteLine("❌ 无法获取数据存储服务");
                    return;
                }

                await dataStorage.LoadAsync();
                var report = await dataStorage.ValidateDataIntegrityAsync();

                Console.WriteLine("数据完整性检查结果:");
                Console.WriteLine($"检查时间: {report.GeneratedAt:yyyy-MM-dd HH:mm:ss}");
                Console.WriteLine($"数据有效: {(report.IsValid ? "✅ 是" : "❌ 否")}");
                Console.WriteLine($"总问题数: {report.TotalIssuesCount}");
                Console.WriteLine();

                if (!string.IsNullOrEmpty(report.ErrorMessage))
                {
                    Console.WriteLine($"❌ 错误信息: {report.ErrorMessage}");
                    return;
                }

                if (report.HasAnyIssues)
                {
                    Console.WriteLine("发现的问题:");
                    
                    if (report.OrphanedDocuments.Count > 0)
                        Console.WriteLine($"  • 孤立文档: {report.OrphanedDocuments.Count} 个");
                    
                    if (report.OrphanedNovelProjects.Count > 0)
                        Console.WriteLine($"  • 孤立小说项目: {report.OrphanedNovelProjects.Count} 个");
                    
                    if (report.OrphanedChapters.Count > 0)
                        Console.WriteLine($"  • 孤立章节: {report.OrphanedChapters.Count} 个");
                    
                    if (report.OrphanedCharacters.Count > 0)
                        Console.WriteLine($"  • 孤立角色: {report.OrphanedCharacters.Count} 个");
                    
                    if (report.OrphanedVectorRecords.Count > 0)
                        Console.WriteLine($"  • 孤立向量记录: {report.OrphanedVectorRecords.Count} 个");
                    
                    if (report.OrphanedWorldSettings.Count > 0)
                        Console.WriteLine($"  • 孤立世界设定: {report.OrphanedWorldSettings.Count} 个");
                    
                    if (report.DuplicateProjectIds.Count > 0)
                        Console.WriteLine($"  • 重复项目ID: {string.Join(", ", report.DuplicateProjectIds)}");
                    
                    if (report.DuplicateDocumentIds.Count > 0)
                        Console.WriteLine($"  • 重复文档ID: {string.Join(", ", report.DuplicateDocumentIds)}");
                    
                    if (report.DuplicateNovelProjectIds.Count > 0)
                        Console.WriteLine($"  • 重复小说项目ID: {string.Join(", ", report.DuplicateNovelProjectIds)}");
                }
                else
                {
                    Console.WriteLine("✅ 数据完整性良好，未发现问题");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 检查失败: {ex.Message}");
            }
        }

        private static async Task RunDataCleanup(TestDataCleanup testCleanup)
        {
            Console.WriteLine("正在执行数据清理...");
            Console.WriteLine();

            try
            {
                var dataStorage = App.ServiceProvider?.GetService<IDataStorageService>();
                if (dataStorage == null)
                {
                    Console.WriteLine("❌ 无法获取数据存储服务");
                    return;
                }

                Console.Write("确定要执行数据清理吗？这将删除所有无效引用 (y/N): ");
                var confirm = Console.ReadLine()?.Trim().ToLower();
                
                if (confirm != "y" && confirm != "yes")
                {
                    Console.WriteLine("操作已取消");
                    return;
                }

                await dataStorage.LoadAsync();
                var result = await dataStorage.CleanupInvalidProjectReferencesAsync();

                Console.WriteLine("数据清理结果:");
                Console.WriteLine($"执行状态: {(result.IsSuccess ? "✅ 成功" : "❌ 失败")}");
                Console.WriteLine($"消息: {result.Message}");
                Console.WriteLine();

                if (result.IsSuccess && result.HasAnyCleanup)
                {
                    Console.WriteLine("清理详情:");
                    
                    if (result.RemovedDocumentsCount > 0)
                        Console.WriteLine($"  • 清理文档: {result.RemovedDocumentsCount} 个");
                    
                    if (result.RemovedNovelProjectsCount > 0)
                        Console.WriteLine($"  • 清理小说项目: {result.RemovedNovelProjectsCount} 个");
                    
                    if (result.RemovedChaptersCount > 0)
                        Console.WriteLine($"  • 清理章节: {result.RemovedChaptersCount} 个");
                    
                    if (result.RemovedCharactersCount > 0)
                        Console.WriteLine($"  • 清理角色: {result.RemovedCharactersCount} 个");
                    
                    if (result.RemovedVectorRecordsCount > 0)
                        Console.WriteLine($"  • 清理向量记录: {result.RemovedVectorRecordsCount} 个");
                    
                    if (result.RemovedWorldSettingsCount > 0)
                        Console.WriteLine($"  • 清理世界设定: {result.RemovedWorldSettingsCount} 个");
                    
                    Console.WriteLine($"  • 总清理数量: {result.TotalRemovedCount} 个");
                }
                else if (result.IsSuccess && !result.HasAnyCleanup)
                {
                    Console.WriteLine("✅ 未发现需要清理的数据");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 清理失败: {ex.Message}");
            }
        }

        private static async Task CreateBackup(TestDataCleanup testCleanup)
        {
            Console.WriteLine("正在创建数据备份...");
            Console.WriteLine();

            try
            {
                var loggerFactory = App.ServiceProvider?.GetService<ILoggerFactory>();
                var dataStorage = App.ServiceProvider?.GetService<IDataStorageService>();
                
                if (loggerFactory == null || dataStorage == null)
                {
                    Console.WriteLine("❌ 无法获取必要的服务");
                    return;
                }

                var cleanupService = new DataCleanupService(dataStorage, loggerFactory.CreateLogger<DataCleanupService>());
                var backup = await cleanupService.CreateBackupAsync("控制台测试备份");

                if (backup != null)
                {
                    Console.WriteLine("✅ 备份创建成功:");
                    Console.WriteLine($"  路径: {backup.BackupPath}");
                    Console.WriteLine($"  大小: {backup.BackupSize / 1024.0:F1} KB");
                    Console.WriteLine($"  时间: {backup.CreatedAt:yyyy-MM-dd HH:mm:ss}");
                }
                else
                {
                    Console.WriteLine("❌ 备份创建失败");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 创建备份失败: {ex.Message}");
            }
        }

        private static async Task ViewBackups(TestDataCleanup testCleanup)
        {
            Console.WriteLine("查看备份列表...");
            Console.WriteLine();

            try
            {
                var loggerFactory = App.ServiceProvider?.GetService<ILoggerFactory>();
                var dataStorage = App.ServiceProvider?.GetService<IDataStorageService>();
                
                if (loggerFactory == null || dataStorage == null)
                {
                    Console.WriteLine("❌ 无法获取必要的服务");
                    return;
                }

                var cleanupService = new DataCleanupService(dataStorage, loggerFactory.CreateLogger<DataCleanupService>());
                var backups = await cleanupService.GetBackupListAsync();

                if (backups.Count == 0)
                {
                    Console.WriteLine("📁 没有找到备份文件");
                    return;
                }

                Console.WriteLine($"找到 {backups.Count} 个备份文件:");
                Console.WriteLine();

                for (int i = 0; i < Math.Min(backups.Count, 10); i++)
                {
                    var backup = backups[i];
                    var fileName = System.IO.Path.GetFileName(backup.BackupPath);
                    var status = backup.IsValid ? "✅" : "❌";
                    
                    Console.WriteLine($"{i + 1,2}. {status} {backup.CreatedAt:yyyy-MM-dd HH:mm:ss} - {backup.BackupSize / 1024.0:F1} KB");
                    Console.WriteLine($"     {fileName}");
                    Console.WriteLine();
                }

                if (backups.Count > 10)
                {
                    Console.WriteLine($"... 还有 {backups.Count - 10} 个备份文件");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 查看备份失败: {ex.Message}");
            }
        }

        private static async Task RunFullTest(TestDataCleanup testCleanup)
        {
            Console.WriteLine("正在运行完整测试...");
            Console.WriteLine();

            try
            {
                await testCleanup.RunTestAsync();
                Console.WriteLine("✅ 完整测试执行完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 完整测试失败: {ex.Message}");
            }
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            // 配置日志
            services.AddLogging(builder =>
            {
                builder.AddConsole();
                builder.SetMinimumLevel(LogLevel.Information);
            });

            // 注册数据存储服务
            services.AddSingleton<IDataStorageService, JsonDataStorageService>();
        }
    }
}
